package cn.ckx.coding.common.utils.redis;

import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * redis工具
 */
public class RedisUtil {

    private static final String COMPARE_AND_DELETE =
            "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                    "then\n" +
                    "    return redis.call('del',KEYS[1])\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";

    private final StringRedisTemplate stringRedisTemplate;

    public RedisUtil(RedisTemplate redisTemplate) {
        this.stringRedisTemplate = new StringRedisTemplate();
        this.stringRedisTemplate.setConnectionFactory(redisTemplate.getConnectionFactory());
        this.stringRedisTemplate.afterPropertiesSet();
    }

    public RedisLock getLock(final String key, int expireSeconds){
        return getLock(key, expireSeconds, 0, 0);
    }

    public RedisLock getLock(final String key, final int expireSeconds, int maxRetryTimes, long retryIntervalTimeMillis){
        final String value = key.hashCode()+"";

        int maxTimes = maxRetryTimes + 1;
        for(int i = 0;i < maxTimes; i++) {
            Boolean status = stringRedisTemplate.execute(
                    (RedisCallback<Boolean>) connection ->  stringRedisTemplate
                            .opsForValue()
                            .setIfAbsent(key, value, expireSeconds, TimeUnit.SECONDS));

            if (status) {
                return new RedisLockInner(stringRedisTemplate, key, value);
            }

            if(retryIntervalTimeMillis > 0) {
                try {
                    Thread.sleep(retryIntervalTimeMillis);
                } catch (InterruptedException e) {
                    break;
                }
            }
            if(Thread.currentThread().isInterrupted()){
                break;
            }
        }

        return null;
    }

    private class RedisLockInner implements RedisLock{

        private StringRedisTemplate stringRedisTemplate;
        private String key;
        private String expectedValue;

        RedisLockInner(StringRedisTemplate stringRedisTemplate, String key, String expectedValue){
            this.stringRedisTemplate = stringRedisTemplate;
            this.key = key;
            this.expectedValue = expectedValue;
        }

        @Override
        public void unlock(){
            List<String> keys = Collections.singletonList(key);
            stringRedisTemplate.execute(new DefaultRedisScript<>(COMPARE_AND_DELETE, Long.class), keys, expectedValue);
        }

        @Override
        public void close() throws Exception {
            this.unlock();
        }
    }
}
